package top.ztf.erp.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import top.ztf.erp.dao.UserDao;
import top.ztf.erp.domain.Permission;
import top.ztf.erp.domain.Role;
import top.ztf.erp.domain.User;
import top.ztf.erp.service.UserService;
import top.ztf.erp.utils.MD5Utils;
import top.ztf.erp.utils.MyBatisUtil;
import top.ztf.erp.utils.TimeUtil;
import top.ztf.erp.vo.PermissionVo;

import java.util.*;

public class UserServiceImp implements UserService {
    @Override
    public PageInfo<User> getUserList(String pageNo, String pageSize) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        PageHelper.startPage(Optional.ofNullable(pageNo).
                        filter(StringUtils::isNumeric).filter(t->!"".equals(t)).
                        map(Integer::parseInt).
                        orElse(1),
                Optional.ofNullable(pageSize).
                        filter(StringUtils::isNumeric).filter(t->!"".equals(t)).
                        map(Integer::parseInt).
                        orElse(5));//执行sql的语句,必须紧挨此方法调用之后

        List<User> listByPage = userDao.getUserListByPage();
        PageInfo<User> rolePageInfo = new PageInfo<>(listByPage);
        sqlSession.clearCache();
        return rolePageInfo;
    }

    @Override
    public User getUserById(String id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        return userDao.getUserById(id);
    }

    @Override
    public int updateUser(User user) {
        user.setEditTime(TimeUtil.getNowTime());
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        try {
            int count = userDao.updateUser(user);
            sqlSession.commit();
            return 1;
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int addUser(User user) {
        user.setCreateTime(TimeUtil.getNowTime());
        user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        try {
            int count = userDao.addUser(user);
            sqlSession.commit();
            return 1;
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public PageInfo<User> searchList(String searchName, String startTime, String endTime, String lock, String pageNo, String pageSize) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        PageHelper.startPage(Optional.ofNullable(pageNo).
                        filter(StringUtils::isNumeric).filter(t->!"".equals(t)).
                        map(Integer::parseInt).
                        orElse(1),
                Optional.ofNullable(pageSize).
                        filter(StringUtils::isNumeric).filter(t->!"".equals(t)).
                        map(Integer::parseInt).
                        orElse(5));//执行sql的语句,必须紧挨此方法调用之后
        List<User> userList = userDao.searchList(searchName, startTime, endTime, lock);
        PageInfo<User> rolePageInfo = new PageInfo<>(userList);
        return rolePageInfo;
    }

    @Override
    public Map<String, Object> getAssignById(String id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<Role> hasRole = userDao.getAssignHasRole(id);// 已分配的角色
        if (hasRole ==null){
            hasRole = Collections.emptyList();
        }
        List<Role> desRole = userDao.getAssignDesRole(hasRole);//未分配的角色

        Map<String,Object> map = new HashMap<>(2);
        map.put("desRole",desRole);
        map.put("hasRole",hasRole);
        return map;
    }

    @Override
    public int updateAssign(String userId, String[] parameterValues) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        try {
            userDao.deleteAssignByUser(userId);
            if (parameterValues!=null){
                // parameterValues!=null 则说明有分配的角色 id,否则,不分配角色id
                userDao.updateAssign(userId,parameterValues);
            }
            sqlSession.commit();
            return 1;
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteUser(String[] parameterValues) {
        if (parameterValues==null){
            return 0;
        }

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        try {
            userDao.deleteUser(parameterValues);
            sqlSession.commit();
            return 1;
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public User login(String account, String password,String ip) {

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.login(account,password);
        if (user==null){
            throw new RuntimeException("账号或密码错误");
        }
        if (user.getLockStatus().equals("0")){
            // 被锁住了
            throw new RuntimeException("账号被锁定");
        }
        if (!StringUtils.isEmpty(user.getExpireTime()) &&user.getExpireTime().compareTo(TimeUtil.getNowTime())<=0){
            // 已过期
            throw new RuntimeException("账号有效期已过");
        }
        if (!StringUtils.isEmpty(user.getAllowIps()) && !user.getAllowIps().contains(ip)){
            throw new RuntimeException("ip访问受限");
        }
        return user;
    }

    @Override
    public List<PermissionVo> getPermissionByUser(String id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<Permission> permissions = userDao.getPermissionByUser(id);
        ArrayList<PermissionVo> permissionVos = new ArrayList<>(permissions.size());
        permissions.forEach(t->permissionVos.add(t.clone(PermissionVo.class)));
        return permissionVos;
    }

    @Override
    public List<Map<String, String>> getPermissionByMenu(User user) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<Map<String, String>> list = userDao.getPermissionByMenu(user);
        for (Map<String, String> menu : list) {
            if (menu.containsKey("url")){
                menu.put("target","navTab");
            }
        }
        return list;
    }

    @Override
    public Set<String> getPermissionByButton(User user) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<Permission> permission = userDao.getPermissionByUser(user.getId());
        Set<String> hashSet = new HashSet<>();
        for (Permission pr : permission) {
            if (!StringUtils.isEmpty(pr.getModuleUrl())){
                hashSet.add(pr.getModuleUrl());
            }
            if (!StringUtils.isEmpty(pr.getOperationUrl())){
                hashSet.add(pr.getOperationUrl());
            }
        }
        return hashSet;
    }

}
